// 2013-9-12上午02:20:35  net.betou.trade.main.dao.agency.impl.AgencyDaoImpl.java

package net.betou.trade.main.dao.agencyorproxy.impl;

import java.util.List;

import net.betou.common.hibernate3.Finder;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.main.dao.agencyorproxy.AgencyDao;

import org.springframework.stereotype.Repository;

/**
 * 
 * @author 叶装装
 */
@Repository
public class AgencyDaoImpl extends DaoImpl implements AgencyDao{

	public AgentAndAdmins findAgency( Integer id ){
		String hql = "from AgentAndAdmins bean where bean.id=? and bean.system=? and bean.justAdmin=? and bean.agencyOrProxy=?";
		return ( AgentAndAdmins ) findUnique( hql, id, false, false, true );
	}
	
	public AgentAndAdmins findBySelf( Integer selfId, Integer id ){
		String hql = "from AgentAndAdmins bean where bean.id=? and bean.parent.id=? and bean.system=? and bean.justAdmin=? and bean.agencyOrProxy=?";
		return ( AgentAndAdmins )findUnique( hql, id, selfId, false, false, true );
	}
	
	public List< AgentAndAdmins > findAgencyList(  Integer parentId, Boolean isTop ){
		String hql = "from AgentAndAdmins bean where bean.system=:system ";
		Finder f = Finder.create( hql );
		f.setParam( "system", false );
		return findList( f, parentId, isTop );
	}
	
	public List< AgentAndAdmins > findAccountList( Integer parentId, Boolean isTop ){
	
		String hql = "from AgentAndAdmins bean where  bean.system=:system ";
		Finder f = Finder.create( hql );
		f.setParam( "system", false );
		
		return findList( f, parentId, isTop );
	}
	
	@SuppressWarnings( "unchecked" )
	private List< AgentAndAdmins >  findList( Finder f, Integer parentId, Boolean isTop ){
		if( isTop != null ){
			if( isTop ){
				f.append( " and bean.parent.id is null" );
			}else{
				f.append( " and bean.parent.id is not null" );
			}
		}
		
		if( parentId != null ){
			f.append( " and bean.parent.id=:id" );
			f.setParam( "id", parentId );
		}
		
		f.append(" order by bean.justAdmin desc");

		return find( f, true );
	}
	
	@SuppressWarnings("unchecked")
	public List< AgentAndAdmins > findListByAdminAndRecomment(AgentAndAdmins aaa, boolean agencyOrProxy ){
		String hql = "select bean from AgentAndAdmins bean join bean.adminExt ae where bean.agencyOrProxy = :agencyOrProxy and (ae.recommentAccount =:username or ae.recommentAgent = :intermediaName) order by bean.id ";
		Finder f = Finder.create( hql );
		f.setParam( "username", aaa.getUsername() );
		f.setParam( "intermediaName" , aaa.getIntermediaName() );
		f.setParam( "agencyOrProxy" , agencyOrProxy );
		return find( f, true );
	}
}
